<template>
  <div>
    <el-tabs type="card" v-model="editableTabsValue" @tab-click="handleClick" @tab-remove="removeResource">
      <el-tab-pane
        v-for="(item) in editableTabs"
        :key="item.name"
        :label="item.title"
        :name="item.name"
        closable>
        <div class="videoExample" v-if="item.title === '视频'">
          <p>{{item.content}}</p>
          <video controls="controls" preload="auto" id="lecture" :src="item.url">
            当前浏览器不支持video直接播放，推荐使用Chrome浏览器进行播放
          </video>
        </div>
        <div v-if="item.title === 'PPT'">
          <p>{{item.content}}</p>
          <iframe
          id="previewPDF" :src="item.url" :download="item.content">
          </iframe>
        </div>
        <div v-if="item.title === '作业'">
          <editTask :taskData="task" :key="time" v-if="refresh"/>
        </div>
      </el-tab-pane>
      <!--
      <el-tab-pane label="直播" name="stream" v-if="chapterData.stream.title">
        <span slot="label">
          直播
          <i class="el-icon-circle-check"
            :style="{'color':0?'#409eff':'grey'}"
          />
        </span>
        直播
        <Video2/>
      </el-tab-pane> -->
      <el-tab-pane name="add">
        <span slot="label">
          <el-dropdown placement="bottom" trigger="click" @command="addResource" @visible-change="showTabContent">
            <span class="el-dropdown-link" style="padding: 8px;font-size:20px;font-weight:bold;">
              +
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item key="video" command="video">添加视频</el-dropdown-item>
              <el-dropdown-item key="ppt" command="ppt">添加PPT</el-dropdown-item>
              <el-dropdown-item key="task" command="task">添加作业</el-dropdown-item>
              <el-dropdown-item key="stream" command="stream" disabled>添加直播</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </span>
      </el-tab-pane>
    </el-tabs>
    <el-dialog
      title="选择资源"
      :visible.sync="dialogVisible"
      width="40%"
      @close="closeDialog">
      <div class="resourceDialog">
          <label>选择资源：</label>
          <el-autocomplete
            class="inline-input"
            v-model="state"
            :fetch-suggestions="querySearch"
            placeholder="请选择资源"
            @select="handleSelect"
            value-key=title
            :popper-append-to-body="false"
            clearable
          ></el-autocomplete>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog()">取 消</el-button>
        <el-button type="primary" @click="saveResource()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import api from '../../../api.js'
import editTask from './task/task-edit.vue'
import Video from './creation/Video.vue'
import Video2 from './creation/Video2.vue'
import PPT from './creation/PPT.vue'

export default {
  name: 'Creation',
  components: { editTask, Video, PPT, Video2 },
  props: ['chapterData'],
  data () {
    return {
      editableTabs: [], // 加载对应节的资源
      editableTabsValue: '', // 默认显示tab的名称
      selectedResource: '',
      dialogVisible: false,
      resourceType: [{value: 'video', label: '视频'}],
      resourceTypeValue: '',
      filteredResource: [],
      state: '',
      baseUrl: '',
      task: {},
      paperDetail: [],
      time: new Date().getTime(),
      refresh: true
    }
  },
  async mounted () {
    this.task = {
      'sectionId': this.chapterData.id,
      'paper': {},
      'paperDetail': [],
      'paperDetailProblems': []
    }
    // 重置本节作业信息
    for (let i = this.chapterData.resources.length - 1; i >= 0; i--) {
      if (this.chapterData.resources[i].genre === 'task') {
        this.chapterData.resources.splice(i, 1)
      }
    }
    // 获取该节下的所有homework (其他资源已从courseResourceArrange页面加载并保存在chapterData中)
    await api['getHomeworks'](this.chapterData.id).then(res => {
      // foreach homework add to chapterData.resources
      res.data.data.forEach(element => {
        this.task.paper = element // 传值给task-edit页面，显示试卷
        // 在前端显示task tab
        element.genre = 'task'
        this.chapterData.resources.push(element)
      })
    })
    // baseurl
    const env = await process.env
    this.baseUrl = env.baseUrl + '/api/course/section?path='
    // 把当前节的课程资源加载到tab上
    if (this.chapterData.resources.length) {
      this.chapterData.resources.forEach(res => {
      // 判断资源类型，添加对应类型的资源
        if (res.genre === 'video') {
          this.editableTabs.push({
            title: '视频',
            name: res.id.toString(),
            content: res.title,
            url: this.baseUrl + res.url})
        } else if (res.genre === 'pdf') {
          this.editableTabs.push({
            title: 'PPT',
            name: res.id.toString(),
            content: res.title,
            url: this.baseUrl + res.url})
        } else if (res.genre === 'task') {
          this.editableTabs.push({
            title: '作业',
            name: '作业' + res.id.toString()})
        }
      })
      this.editableTabsValue = this.editableTabs[0].name // 默认当前显示tab的名字
    }
  },
  methods: {
    // 点击tab的操作
    async handleClick (tab, event) {
      if (tab.name === 'addResource') {
        this.addResource()
      } else {
        this.editableTabsValue = tab.name // 切换到被点击的tab
        // 当点击的tab是作业时，拿到作业中的全部题目
        if (tab.name.substr(0, 2) === '作业') {
          await this.loadHomework(tab.name)
        }
      }
    },
    async loadHomework (tabname) {
      this.task.paperDetail = [] // 重置作业题
      this.task.paperDetailProblems = []
      this.task.tabname = tabname
      // 请求作业下的全部习题信息
      await api['getHomeworkDetail'](tabname.slice(2)).then(res => {
        // 传递作业数据到task-edit页面
        this.task.paper.id = res.data.data.homeworkId
        this.task.paper.title = res.data.data.title
        // 单选多选，判断
        if (res.data.data.selectionProblems) {
          res.data.data.selectionProblems.forEach(e => {
            this.task.paperDetail.push(JSON.parse(JSON.stringify(
              {
                id: e.selectionProblem.id,
                subject: e.selectionProblem.description,
                options: e.selectionProblem.choices,
                answer: e.selectionProblem.answers,
                studentAnswer: '',
                analysis: '',
                score: parseInt(e.score),
                selection_problem_type: e.selectionProblem.selectionProblemType,
                isEdit: false
              }
            )))
          })
        }
        // 程序设计题
        if (res.data.data.problems) {
          res.data.data.problems.forEach(e => {
            this.task.paperDetailProblems.push(JSON.parse(JSON.stringify(
              {
                programmingQuestionId: e.problem.id,
                analysis: '',
                score: parseInt(e.score),
                isEdit: false,
                programmingQuestionInfo: e.problem
              }
            )))
          })
        }
      })
      this.refresh = false
      this.$nextTick(() => {
        this.refresh = true
      })
    },
    // 点击加号，根据选择的下拉资源类型，筛选可用资源
    addResource (dropdownItem) {
      // 筛选视频类型可用资源
      switch (dropdownItem) {
        case 'video': {
          this.filterResource('video')
          break
        }
        case 'ppt': {
          this.filterResource('pdf')
          break
        }
        case 'task': {
          this.saveResource('task')
          break
        }
      }
      this.state = ''
    },
    showTabContent (e) {
      if (!e && this.editableTabs[0]) {
        this.editableTabsValue = this.editableTabs[0].name // 默认当前显示tab的名字
      }
    },
    removeResource (targetName) {
      this.$confirm('是否确定删除当前选中课程资源?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 删除资源
        if (parseFloat(targetName[0]).toString() === 'NaN') {
          // 删除作业
          api.deleteHomework(this.chapterData.id, parseInt(targetName.slice(2))).then(res => {
            this.deleteTab(targetName)
          }).catch(() => {
            // 提示不可以删除的信息
            this.$message({
              type: 'error',
              message: '学生已经提交了作业，不能删除该作业'
            })
          })
        } else {
          // 删除其他资源类型
          api.delSectionResource(this.chapterData.id, parseInt(targetName)).then(res => {
            this.deleteTab(targetName)
          })
        }
      }).catch(() => {
      })
    },
    // 从页面上删除目标tab
    deleteTab (targetName) {
      // 页面删除tab
      let tabs = this.editableTabs
      let activeName = this.editableTabsValue
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1]
            if (nextTab) {
              activeName = nextTab.name
            }
          }
        })
      }
      this.editableTabsValue = activeName
      this.editableTabs = tabs.filter(tab => tab.name !== targetName)
      // 刷新页面
      this.loadHomework(activeName)
      // 提示信息
      this.$message({
        type: 'success',
        message: '删除成功!'
      })
    },
    // 关闭选择视频资源对话框
    closeDialog () {
      this.dialogVisible = false
      this.selectedResource = {}
      this.filteredResource = []
    },
    saveResource (a) {
      // 设置默认参数
      var filetype = arguments[0] ? arguments[0] : 0
      if (filetype) {
        // 生成作业
        let passData = {
          section_id: this.chapterData.id,
          title: '北软信息职业技术学院试卷模板',
          course_id: this.$route.params.courseId
        }
        api['createHomework'](passData).then(res => {
          this.editableTabs.push({
            title: '作业',
            name: '作业' + res.data.data.id.toString()
          })
        }).then(_ => {
          this.editableTabsValue = this.editableTabs[this.editableTabs.length - 1].name // 切换到最新添加的tab
          this.loadHomework(this.editableTabsValue) // 刷新页面
        }).catch(e => {
        })
      } else {
        // 生成视频、ppt
        // 发送数据到后端
        let passData = {
          section: this.chapterData.id,
          resource: this.selectedResource.id
        }
        // 判断选中的资源是否已存在
        if (this.editableTabs.filter(tab => tab.name === this.selectedResource.id.toString()).length) {
          this.filteredResource = []
          this.dialogVisible = false
          return this.$alert('选中的资源已经添加了', '注意', {
            confirmButtonText: '确定'
          })
        }
        api['matchSectionAndResource'](passData).then(res => {
          // 添加一个新的tab
          if (this.selectedResource.genre === 'video') {
            return this.editableTabs.push({
              title: '视频',
              name: this.selectedResource.id.toString(),
              content: this.selectedResource.title,
              url: this.baseUrl + this.selectedResource.url
            })
          } else if (this.selectedResource.genre === 'pdf') {
            return this.editableTabs.push({
              title: 'PPT',
              name: this.selectedResource.id.toString(),
              content: this.selectedResource.title,
              url: this.baseUrl + this.selectedResource.url
            })
          }
        }).then(_ => {
          this.dialogVisible = false
          // 切换到最新添加的tab
          this.editableTabsValue = this.editableTabs[this.editableTabs.length - 1].name
          // 重置筛选资源
          this.filteredResource = []
        }).catch(e => {
        })
      }
    },
    // 保存选中的资源
    handleSelect (item) {
      this.selectedResource = item
    },

    // 判断当前课程是否存在资源，不存在则弹出warning
    filterResource (resourceType) {
      api['getCourseResourceInfo'](this.$route.params.courseId, '', resourceType).then(res => {
        this.filteredResource = res.data.data.results
        if (this.filteredResource.length === 0) {
          this.$message({
            message: '当前课程没有相应资源，请先在资源管理页面添加！',
            type: 'warning'
          })
        } else {
          this.dialogVisible = true
        }
      })
    },

    // 自定义input搜索筛选框
    querySearch (queryString, cb) {
      var results = queryString ? this.filteredResource.filter(this.createFilter(queryString)) : this.filteredResource
      // 调用 callback 返回建议列表的数据
      cb(results)
    },

    createFilter (queryString) {
      return (resourceTitle) => {
        return (resourceTitle.title.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    }
  }
}
</script>

<style>
  .videoExample video{
    width: 85%;
    border: 1px solid lightgrey;
  }

  #previewPDF{
    height: 100vh;
    width: 85%;
  }
</style>
